package contact

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/common/usermetadata"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/dto/contact"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/business_opportunity/contact"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/business_opportunity/subscription/radar"
	customerRepo "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/clue/customer"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/bigdata_remote"
	opensearch_remote2 "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/opensearch_remote"
	pb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"git.myscrm.cn/golang/stark/v4"
	"strconv"
	"strings"
	"sync"
)

type contactService struct {
	radarSubscriptionConfigRepos radar.GfyxRadarSubscriptionConfigReposIface
	opTelViewHistoryRepos        contact.GfyxOpTelViewHistoryReposIface
	customerPoolRepos            customerRepo.CustomerPoolRepoIface
	openSearchRepos              opensearch_remote2.OpenSearchRepositoryIface
	RadarSubscriptionConfigRepos radar.GfyxRadarSubscriptionConfigReposIface
	bigDataServiceRepo           bigdata_remote.BigDataServiceRepositoryIface
}

func NewContactService(
	radarSubscriptionConfigRepos radar.GfyxRadarSubscriptionConfigReposIface,
	opTelViewHistoryRepos contact.GfyxOpTelViewHistoryReposIface,
	customerPoolRepos customerRepo.CustomerPoolRepoIface,
	openSearchRepos opensearch_remote2.OpenSearchRepositoryIface,
	RadarSubscriptionConfigRepos radar.GfyxRadarSubscriptionConfigReposIface,
	bigDataServiceRepo bigdata_remote.BigDataServiceRepositoryIface,
) ContactServiceIface {
	return &contactService{
		radarSubscriptionConfigRepos: radarSubscriptionConfigRepos,
		opTelViewHistoryRepos:        opTelViewHistoryRepos,
		customerPoolRepos:            customerPoolRepos,
		openSearchRepos:              openSearchRepos,
		RadarSubscriptionConfigRepos: RadarSubscriptionConfigRepos,
		bigDataServiceRepo:           bigDataServiceRepo,
	}
}

// ContactList 获取联系人列表
func (s *contactService) ContactList(ctx context.Context, request *pb.ContactListRequest) (*pb.ContactListResponse, error) {
	resp := pb.ContactListResponse{ContactList: make([]*pb.ContactDataList, 0), CooperationCompany: make([]*pb.CooperationCompanyList, 0)}
	metaUserInfo := usermetadata.GetMetaUserInfo(ctx)
	radarSubscriptionConfig, err := s.radarSubscriptionConfigRepos.GetRadarSubscriptionConfigByUser(ctx, metaUserInfo.TenantUserUid)
	if err != nil {
		stark.Logger.Error(ctx, "获取gfyx_radarsubscriptionconfig异常,err:", err)
	}
	companyName, organizingCode, currentCompanyName, currentOrganizingCode, winbidCompanyName, winbidOrganizingCode := s.getCompanyName(ctx, request)
	if currentCompanyName == "" && currentOrganizingCode == "" {
		return &resp, nil
	}
	//调用opensearch接口
	binOwnerMobile := s.getPurchaseMobile(ctx, request.PurchaseOwnerMobile)
	contactParam := &opensearch_remote2.GetContactListRequest{
		CompanyName:           companyName,
		OrganizingCode:        organizingCode,
		CurrentCompanyName:    currentCompanyName,
		CurrentOrganizingCode: currentOrganizingCode,
		SubscriptProvinceCode: radarSubscriptionConfig.AreaCode,
		SubscriptCityCode:     radarSubscriptionConfig.AreaCode,
		BidKeyword:            radarSubscriptionConfig.BidKeyword,
		SearchKeyword:         request.Keyword,
		PhoneType:             request.PhoneType,
		ProvinceCode:          request.ProvinceCode,
		CityCode:              request.CityCode,
		AreaCode:              request.AreaCode,
		BidOwnerMobile:        binOwnerMobile,
		Page:                  request.Page,
		PageSize:              request.PageSize,
	}

	cooperationParam := &opensearch_remote2.GetCooperationListRequest{
		CurrentCompanyName:    currentCompanyName,
		CurrentOrganizingCode: currentOrganizingCode,
		SubscriptProvinceCode: radarSubscriptionConfig.AreaCode,
		SubscriptCityCode:     radarSubscriptionConfig.AreaCode,
		BidKeyword:            radarSubscriptionConfig.BidKeyword,
		SearchKeyword:         request.Keyword,
		PhoneType:             request.PhoneType,
		ProvinceCode:          request.ProvinceCode,
		CityCode:              request.CityCode,
		AreaCode:              request.AreaCode,
		BidOwnerMobile:        binOwnerMobile,
		Page:                  request.Page,
		PageSize:              request.PageSize,
	}

	contactResult := &opensearch_remote2.GetContactListData{}
	// todo cooperationResult 可能为nil
	cooperationResult := &opensearch_remote2.GetCooperationListData{}
	cooperationCompany := make([]*bigdata_remote.GetCooperationCompanyItem, 0)
	switch request.ContactType {
	case "single_developer":
		contactParam.IsDeveloper = 1
		contactResult, err = s.openSearchRepos.GetContactList(ctx, contactParam)
		if err != nil {
			return nil, err
		}
		break
	case "single_supplier":
		contactParam.IsSupplier = 1
		contactResult, err = s.openSearchRepos.GetContactList(ctx, contactParam)
		if err != nil {
			return nil, err
		}
	case "single_customer": //客户 = 开发商+工程单位
		contactParam.ScoreWeight = constants.ContactScoreWeightDeveloper
		if request.JobType == constants.ContactJobTypeDeveloper {
			contactParam.IsDeveloper = 1
		} else if request.JobType == constants.ContactJobTypeSupplier {
			contactParam.IsSupplier = 1
		}
		contactResult, err = s.openSearchRepos.GetContactList(ctx, contactParam)
		if err != nil {
			return nil, err
		}
		break
	case "multi_supplier":
		if len(request.Company) == 4 { //中标特殊处理
			contactParam.IsSupplier = 1
			contactParam.CompanyName = winbidCompanyName
			contactParam.OrganizingCode = winbidOrganizingCode
			contactParam.PageSize = 100
			contactResult, err = s.openSearchRepos.GetContactList(ctx, contactParam)
			if err != nil {
				return nil, err
			}
		} else {
			cooperationCompany = s.getCooperationName(ctx, currentCompanyName, cooperationParam, request)
			cooperationParam.IsSupplier = 1

			if len(cooperationParam.CompanyList) <= 0 {
				return &resp, nil
			}
			//合作单位搜索词，不过滤联系人数据
			cooperationParam.SearchKeyword = ""
			cooperationResult, err = s.openSearchRepos.GetCooperationList(ctx, cooperationParam)
			if err != nil {
				return nil, err
			}
		}
		break
	case "developer_and_supplier":
		//全部：开发商和供应商
		//go 多协程请求
		wg := sync.WaitGroup{}
		for i := 0; i <= 1; i++ {
			wg.Add(1)
			//1、联系人
			if i == 0 {
				go func() {
					contactParam.IsDeveloper = 1
					developerContactList, err := s.openSearchRepos.GetContactList(ctx, contactParam)
					if err != nil {
						stark.Logger.Error(ctx, "opensearch contact/recommend,%s", err.Error())
					}
					contactResult.Total = developerContactList.Total
					if developerContactList.Total > 0 {
						for _, v := range developerContactList.List {
							contactResult.List = append(contactResult.List, v)
						}
					}
					wg.Done()
				}()
			}
			//2、合作单位
			if i == 1 {
				go func() {
					if len(request.Company) == 4 { //中标特殊处理
						contactParam2 := &opensearch_remote2.GetContactListRequest{
							CompanyName:           winbidCompanyName,
							OrganizingCode:        winbidOrganizingCode,
							CurrentCompanyName:    "",
							CurrentOrganizingCode: "",
							SubscriptProvinceCode: contactParam.SubscriptProvinceCode,
							SubscriptCityCode:     contactParam.SubscriptCityCode,
							BidKeyword:            contactParam.BidKeyword,
							SearchKeyword:         contactParam.SearchKeyword,
							PhoneType:             contactParam.PhoneType,
							ProvinceCode:          contactParam.ProvinceCode,
							CityCode:              contactParam.CityCode,
							AreaCode:              contactParam.AreaCode,
							BidOwnerMobile:        contactParam.BidOwnerMobile,
							Page:                  1,
							PageSize:              100,
							IsDeveloper:           0,
							IsSupplier:            1,
						}
						winBidContactResult := &opensearch_remote2.GetContactListData{}
						winBidContactResult, err = s.openSearchRepos.GetContactList(ctx, contactParam2)
						if err != nil {
							stark.Logger.Error(ctx, "opensearch contact/recommend,%s", err.Error())
						}

						if winBidContactResult.Total > 0 {
							for _, v := range winBidContactResult.List {
								contactResult.List = append(contactResult.List, v)
							}
						}
					} else { //正常情况下
						cooperationCompany = s.getCooperationName(ctx, currentCompanyName, cooperationParam, request)
						//合作单位
						cooperationParam.IsSupplier = 1
						if len(cooperationParam.CompanyList) > 0 {
							cooperationResult, err = s.openSearchRepos.GetCooperationList(ctx, cooperationParam)
							if err != nil {
								stark.Logger.Error(ctx, "opensearch contact/cooperation-list,%s", err.Error())
							}
						}

					}

					wg.Done()
				}()
			}

		}
		wg.Wait()
		break
	default:

	}
	//联系人:手机号查看次数、手机号打码
	if contactResult.Total > 0 {
		mobileList := make([]string, 0)
		for _, contactValue := range contactResult.List {
			mobileList = append(mobileList, contactValue.PhoneNumber)
		}
		mobileViewTimes, err := s.opTelViewHistoryRepos.GetOpTelViewHistoryBatch(ctx, mobileList, metaUserInfo.TenantUserUid)
		if err != nil {
			stark.Logger.Error(ctx, "获取gfyx_optelviewhistory异常,err:", err)
			return &resp, err
		}
		for _, contactValue := range contactResult.List {
			contactValue.ViewTimes = mobileViewTimes[contactValue.PhoneNumber]
			if mobileViewTimes[contactValue.PhoneNumber] <= 0 { //如果手机号，没有被查看过，则需要打码
				contactValue.PhoneNumber = utils.GetMobileEncrypt(contactValue.PhoneNumber)
			}
		}
	}

	//合作单位:手机号查看次数、手机号打码
	if cooperationResult.Total > 0 {
		cooperationMobileList := make([]string, 0)
		companyName := make([]string, 0)
		for _, cooperationValue := range cooperationResult.List {
			for _, ccvalue := range cooperationValue.Contact {
				cooperationMobileList = append(cooperationMobileList, ccvalue.PhoneNumber)
			}
			cooperationValue.CompanyType = "supplier"
			companyName = append(companyName, cooperationValue.CooperationCompanyName)
		}

		cooperationMobileViewTimes, err := s.opTelViewHistoryRepos.GetOpTelViewHistoryBatch(ctx, cooperationMobileList, metaUserInfo.TenantUserUid)
		if err != nil {
			stark.Logger.Error(ctx, "获取gfyx_optelviewhistory异常,err:", err)
			return &resp, err
		}

		for _, cooperationValue := range cooperationResult.List {
			for _, ccvalue := range cooperationValue.Contact {
				ccvalue.ViewTimes = cooperationMobileViewTimes[ccvalue.PhoneNumber]
				if cooperationMobileViewTimes[ccvalue.PhoneNumber] <= 0 { //如果手机号，没有被查看过，则需要打码
					ccvalue.PhoneNumber = utils.GetMobileEncrypt(ccvalue.PhoneNumber)
				}
			}
			cooperationValue.CompanyType = "supplier"

			//合作信息
			for _, cooperationCntValue := range cooperationCompany {
				if cooperationValue.CooperationCompanyName == cooperationCntValue.SupplierName {
					cooperationValue.CooperationCnt = cooperationCntValue.Total
					cooperationValue.LastCooperationTime = cooperationCntValue.LastCooperationTime
					cooperationValue.ContactCnt = cooperationCntValue.SupplierContactNum
				}
			}
		}
	}

	//返回结果:联系人
	for _, item := range contactResult.List {
		pbContact := &pb.ContactDataList{
			PulsarTime:              item.PulsarTime,
			Id:                      item.Id,
			DataTime:                item.DataTime,
			CompanyName:             item.CompanyName,
			Name:                    item.Name,
			OrganizingCode:          item.OrganizingCode,
			PhoneNumber:             item.PhoneNumber,
			Position:                item.Position,
			PurchaseOwner:           item.PurchaseOwner,
			SourceId:                item.SourceId,
			IsSupplier:              item.IsSupplier,
			Email:                   item.Email,
			IsDeveloper:             item.IsDeveloper,
			IsRecommend:             item.IsRecommend,
			CooperationCnt:          item.CooperationCnt,
			CooperationSubscriptCnt: item.CooperationSubscriptCnt,
			BiddingCnt:              item.BiddingCnt,
			BiddingSubscriptCnt:     item.BiddingSubscriptCnt,
			ViewTimes:               item.ViewTimes,
			NameHL:                  item.NameHL,
			CompanyNameHL:           item.CompanyNameHL,
			CooperationTitleHL:      item.CooperationTitleHL,
			XScore:                  item.Score,
		}
		//采购线、销售线
		jobType := make([]*pb.JobType, 0)
		if pbContact.IsDeveloper == 1 {
			jobType = append(jobType, &pb.JobType{JobName: constants.ContactJobTypeDeveloper, Remark: constants.ContactJobTypeDeveloperRemark})
		}
		if pbContact.IsSupplier == 1 {
			jobType = append(jobType, &pb.JobType{JobName: constants.ContactJobTypeSupplier, Remark: constants.ContactJobTypeSupplierRemark})
		}
		pbContact.JobType = jobType
		for _, cooperation := range item.Cooperation {
			pbContact.Cooperation = append(pbContact.Cooperation, &pb.CooperationList{
				Title:                     cooperation.Title,
				SourceId:                  cooperation.SourceId,
				CooperationCompanyName:    cooperation.CooperationCompanyName,
				CooperationOrganizingCode: cooperation.CooperationOrganizingCode,
				Province:                  cooperation.Province,
				ProvinceCode:              cooperation.ProvinceCode,
				City:                      cooperation.City,
				CityCode:                  cooperation.CityCode,
				CooperationTime:           cooperation.CooperationTime,
				Category:                  cooperation.Category,
				SourceType:                cooperation.SourceType,
				Weight:                    cooperation.Weight,
				CompanyName:               item.CompanyName,
				OrganizingCode:            item.OrganizingCode,
				TitleHL:                   cooperation.TitleHL,
			})
		}
		resp.ContactList = append(resp.ContactList, pbContact)
	}
	resp.ContactTotal = contactResult.Total

	//返回结果:合作单位
	for _, item := range cooperationResult.List {
		pbCompany := &pb.CooperationCompanyList{
			CooperationCompanyName:    item.CooperationCompanyName,
			CooperationOrganizingCode: item.CooperationOrganizingCode,
			LastCooperationTime:       item.LastCooperationTime,
			CooperationCnt:            item.CooperationCnt,
			ContactCnt:                item.ContactCnt,
			DocCount:                  item.DocCount,
			XMaxScore:                 item.XMaxScore,
			CompanyType:               item.CompanyType,
		}
		for _, contactItem := range item.Contact {
			pbContact := &pb.ContactDataList{
				PulsarTime:              contactItem.PulsarTime,
				Id:                      contactItem.Id,
				DataTime:                contactItem.DataTime,
				CompanyName:             contactItem.CompanyName,
				Name:                    contactItem.Name,
				OrganizingCode:          contactItem.OrganizingCode,
				PhoneNumber:             contactItem.PhoneNumber,
				Position:                contactItem.Position,
				PurchaseOwner:           contactItem.PurchaseOwner,
				SourceId:                contactItem.SourceId,
				IsSupplier:              contactItem.IsSupplier,
				Email:                   contactItem.Email,
				IsDeveloper:             contactItem.IsDeveloper,
				IsRecommend:             contactItem.IsRecommend,
				CooperationCnt:          contactItem.CooperationCnt,
				CooperationSubscriptCnt: contactItem.CooperationSubscriptCnt,
				BiddingCnt:              contactItem.BiddingCnt,
				BiddingSubscriptCnt:     contactItem.BiddingSubscriptCnt,
				LastCooperationTime:     contactItem.LastCooperationTime,
				ViewTimes:               contactItem.ViewTimes,
				NameHL:                  contactItem.NameHL,
				CompanyNameHL:           contactItem.CompanyNameHL,
				CooperationTitleHL:      contactItem.CooperationTitleHL,
				XScore:                  contactItem.XScore,
			}
			for _, cooperation := range contactItem.Cooperation {
				pbCooperation := &pb.CooperationList{
					Title:                     cooperation.Title,
					SourceId:                  cooperation.SourceId,
					CooperationCompanyName:    cooperation.CooperationCompanyName,
					CooperationOrganizingCode: cooperation.CooperationOrganizingCode,
					Province:                  cooperation.Province,
					ProvinceCode:              cooperation.ProvinceCode,
					City:                      cooperation.City,
					CityCode:                  cooperation.CityCode,
					CooperationTime:           cooperation.CooperationTime,
					Category:                  cooperation.Category,
					SourceType:                cooperation.SourceType,
					Weight:                    cooperation.Weight,
					CompanyName:               cooperation.CompanyName,
					OrganizingCode:            cooperation.OrganizingCode,
					TitleHL:                   cooperation.TitleHL,
				}
				pbContact.Cooperation = append(pbContact.Cooperation, pbCooperation)
			}
			pbCompany.Contact = append(pbCompany.Contact, pbContact)
		}
		resp.CooperationCompany = append(resp.CooperationCompany, pbCompany)
	}
	resp.CooperationCompanyTotal = cooperationResult.Total
	return &resp, nil
}

func (s *contactService) getPurchaseMobile(ctx context.Context, purchaseId string) string {
	bigDataRequest := &bigdata_remote.GetPurchaseBaseRequest{
		Id:       purchaseId,
		PageNum:  1,
		PageSize: 1,
	}
	bigDataFeedResponse, err := s.bigDataServiceRepo.GetPurchaseBase(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Error(ctx, "bigdata GetPurchaseBase,err:%s", err.Error())
	}
	if bigDataFeedResponse != nil && bigDataFeedResponse.Total > 0 {
		return bigDataFeedResponse.List[0].OwerMobile
	}
	return ""
}

func (s *contactService) getCooperationCnt(ctx context.Context, cooperationCompanyName string, companyName []string) ([]*dto.CooperationCntData, error) {
	cooperationCnt := &dto.BigDataCooperationCntRequest{
		CooperationCompanyName: cooperationCompanyName,
		CompanyName:            strings.Join(companyName, ","),
	}
	cooperationCntMap, _ := simplecopier.StructToMapByJsonTag(cooperationCnt)
	cooperationCntResult := &dto.BigDataCooperationCntResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathContactCooperationCnt, cooperationCntMap, map[string]string{}).EndStruct(&cooperationCntResult)
	if len(errs) > 0 {
		stark.Logger.Error(ctx, "获取数芯接口", constants.BigDataPathContactCooperationCnt, "异常,err:", errs[0])
		return make([]*dto.CooperationCntData, 0), errs[0]
	}
	return cooperationCntResult.Data, nil
}

/*
*
return : 公司名称、公司信用代码、当前公司名称、当前公司信用代码、中标公司名称（中标场景）
*/
func (s *contactService) getCompanyName(ctx context.Context, request *pb.ContactListRequest) (string, string, string, string, string, string) {
	var (
		companyName           string
		organizingCode        string
		currentCompanyName    string
		currentOrganizingCode string
		winbidCompanyName     string
		winbidOrganizingCode  string
	)
	if len(request.Company) == 4 { //传多个公司，只有中标场景的乙方联系人
		nameArr := make([]string, 0)
		codeArr := make([]string, 0)
		for k, v := range request.Company {
			if k > 0 {
				if v.CompanyName != "" {
					nameArr = append(nameArr, v.CompanyName)
				}
				if v.OrganizingCode != "" {
					codeArr = append(codeArr, v.OrganizingCode)
				}
			}

		}
		winbidCompanyName = strings.Join(nameArr, ",")
		winbidOrganizingCode = strings.Join(codeArr, ",")
		currentOrganizingCode = request.Company[0].OrganizingCode
		currentCompanyName = request.Company[0].CompanyName
		organizingCode = request.Company[0].OrganizingCode
		companyName = request.Company[0].CompanyName

	} else {
		for k, v := range request.Company {
			if k == 0 {
				currentCompanyName = v.CompanyName
				currentOrganizingCode = v.OrganizingCode
			}
		}
		//获取股权公司，工程单位不带股权，开发商待股权
		if request.ContactType == "single_supplier" || request.ContactType == "multi_supplier" {
			companyName = currentCompanyName
			organizingCode = currentOrganizingCode
		} else if currentOrganizingCode != "" {
			bigDataRequest := &bigdata_remote.GetInvestCompanyRequest{
				OrganizingCode: currentOrganizingCode,
				PageNum:        1,
				PageSize:       10000, //设置1w加股权公司，可修改
			}

			bigDataInvestCompanyResponse, err := s.bigDataServiceRepo.GetInvestCompany(ctx, bigDataRequest)
			if err != nil {
				stark.Logger.Error(ctx, "bigdata GetInvestCompany,err:%s", err.Error())
			}

			SubNameArr := make([]string, 0)
			SubCodeArr := make([]string, 0)
			if bigDataInvestCompanyResponse != nil && bigDataInvestCompanyResponse.Total > 0 {
				for _, investV := range bigDataInvestCompanyResponse.List {
					if investV.SubCompanyName != "" {
						SubNameArr = append(SubNameArr, investV.SubCompanyName)
					}

					if investV.SubOrganizingCode != "" {
						SubCodeArr = append(SubCodeArr, investV.SubOrganizingCode)
					}
				}
			} else { //如果没有股权信息，当前公司
				SubNameArr = append(SubNameArr, currentCompanyName)
				SubCodeArr = append(SubCodeArr, currentOrganizingCode)
			}
			companyName = strings.Join(SubNameArr, ",")
			organizingCode = strings.Join(SubCodeArr, ",")
		} else {
			companyName = currentCompanyName
			organizingCode = currentOrganizingCode
		}

	}

	return companyName, organizingCode, currentCompanyName, currentOrganizingCode, winbidCompanyName, winbidOrganizingCode
}

// ContactDetail 获取联系人详情
func (s *contactService) ContactDetail(ctx context.Context, request *pb.ContactDetailRequest) (*pb.ContactDetailResponse, error) {
	resp := &pb.ContactDetailResponse{}

	requestMap, _ := simplecopier.StructToMapByJsonTag(request)
	contactResult := &dto.BigDataContactResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathContactList, requestMap, map[string]string{}).EndStruct(&contactResult)
	if len(errs) > 0 {
		stark.Logger.Error(ctx, "获取数芯接口", constants.BigDataPathContactList, "异常,err:", errs[0])
	}
	metaUserInfo := usermetadata.GetMetaUserInfo(ctx)
	for _, v := range contactResult.Data.Rows {

		viewTelPhone, err := s.opTelViewHistoryRepos.GetOpTelViewHistory(ctx, v.PhoneNumber, metaUserInfo.TenantUserUid)
		if err != nil {

		}
		if viewTelPhone != nil {
			v.ViewTimes = viewTelPhone.ViewTimes
		}

	}
	resp.List = contactResult.Data.Rows
	return resp, nil
}

// GetMobile 获取手机号
func (s *contactService) GetMobile(ctx context.Context, request *pb.GetMobileRequest) (*pb.GetMobileResponse, error) {
	//手机好查看次数
	metaUserInfo := usermetadata.GetMetaUserInfo(ctx)
	subConfig, _ := s.RadarSubscriptionConfigRepos.GetRadarSubscriptionConfigByUser(ctx, metaUserInfo.TenantUserUid)

	getContactListRequest := &opensearch_remote2.GetContactListRequest{
		Id:       request.Id,
		Page:     1,
		PageSize: 1,
	}
	if subConfig != nil && subConfig.BidKeyword != "" {
		getContactListRequest.BidKeyword = subConfig.BidKeyword
	}

	contactResult, err := s.openSearchRepos.GetContactList(ctx, getContactListRequest)
	if err != nil {
		return nil, err
	}
	if contactResult == nil || len(contactResult.List) == 0 {
		return nil, errors.New("联系人不存在")
	}
	contactItem := contactResult.List[0]

	viewTelPhone, _ := s.opTelViewHistoryRepos.GetOpTelViewHistory(ctx, contactItem.PhoneNumber, metaUserInfo.TenantUserUid)
	if viewTelPhone != nil && viewTelPhone.OpTelViewHistoryGUID == "" {
		viewTelPhone.ViewTimes = 0
		viewTelPhone.TelNumber = contactItem.PhoneNumber
		viewTelPhone.CreatedGUID = metaUserInfo.TenantUserUid
		viewTelPhone.CreatedName = metaUserInfo.UserName
		err = s.opTelViewHistoryRepos.SaveOpTelViewHistory(ctx, viewTelPhone)
		if err != nil {
			stark.Logger.Error(ctx, "新增gfyx_optelviewhistory,err:", err)
		}

	}
	//更新次数
	if !request.IgnoreCount { //不忽略的时候，需要更新次数
		_, err = s.opTelViewHistoryRepos.UpdateViewTimes(ctx, contactItem.PhoneNumber, metaUserInfo.TenantUserUid)
		if err != nil {
			stark.Logger.Error(ctx, "更新gfyx_optelviewhistory,err:", err)
		}
		viewTelPhone.ViewTimes += 1
	}
	if contactItem.Name == "" {
		contactItem.Name = "未知"
	}
	resp := &pb.GetMobileResponse{
		PulsarTime:              contactItem.PulsarTime,
		Id:                      contactItem.Id,
		DataTime:                contactItem.DataTime,
		CompanyName:             contactItem.CompanyName,
		Name:                    contactItem.Name,
		OrganizingCode:          contactItem.OrganizingCode,
		PhoneNumber:             contactItem.PhoneNumber,
		Position:                contactItem.Position,
		SourceId:                contactItem.SourceId,
		IsSupplier:              contactItem.IsSupplier,
		Email:                   contactItem.Email,
		IsDeveloper:             contactItem.IsDeveloper,
		IsRecommend:             contactItem.IsRecommend,
		CooperationCnt:          contactItem.CooperationCnt,
		CooperationSubscriptCnt: contactItem.CooperationSubscriptCnt,
		BiddingCnt:              contactItem.BiddingCnt,
		BiddingSubscriptCnt:     contactItem.BiddingSubscriptCnt,
		ViewTimes:               viewTelPhone.ViewTimes,
	}
	return resp, nil
}

// CooperationList 获取合作案例列表
func (s *contactService) CooperationList(ctx context.Context, request *pb.CooperationListRequest) (*pb.CooperationListResponse, error) {
	resp := &pb.CooperationListResponse{}
	bigDataRequest := &dto.BigDataCooperationRequest{}
	simplecopier.CopyToStruct(bigDataRequest, request) //为什么要转一次结构体，因为数芯的分页参数是 pageNum、pageSize，和接口不一样
	requestMap, _ := simplecopier.StructToMapByJsonTag(bigDataRequest)
	cooperationResult := &dto.BigDataCooperationResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathContactCooperation, requestMap, map[string]string{}).EndStruct(&cooperationResult)
	if len(errs) > 0 {
		stark.Logger.Error(ctx, "获取数芯接口", constants.BigDataPathContactList, "异常,err:", errs[0])
	}
	resp.List = cooperationResult.Data.Rows
	resp.Total = cooperationResult.Data.TotalNum
	return resp, nil
}

// CompanyContactCnt 公司联系人数量
func (s *contactService) CompanyContactCnt(ctx context.Context, request *pb.CompanyContactCntRequest) (*pb.CompanyContactCntResponse, error) {
	resp := &pb.CompanyContactCntResponse{}
	requestMap, _ := simplecopier.StructToMapByJsonTag(request)
	companyContactCntResult := &dto.BigDataCompanyContactCntResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathCompanyContactCnt, requestMap, map[string]string{}).EndStruct(&companyContactCntResult)
	if len(errs) > 0 {
		stark.Logger.Error(ctx, "获取数芯接口", constants.BigDataPathCompanyContactCnt, "异常,err:", errs[0])
	}
	resp.List = companyContactCntResult.Data
	return resp, nil
}

// 获取合作公司列表
// 1-5、6-10、10次以上
func (s *contactService) getNumCondition(numList []*pb.CooperationCount) (int32, int32, int32, int32) {
	if len(numList) == 0 {
		return 0, 0, 0, 0
	}
	var rangeMin int32
	var rangeMax int32
	var notRangeMin int32
	var notRangeMax int32

	for k, v := range numList {
		if k == 0 { //最小值
			rangeMin = v.Min
		}
		if k == len(numList)-1 { //最大值
			rangeMax = v.Max
			if rangeMax == 0 {
				rangeMax = 10000
			}
		}

		if k >= 1 && numList[k].Min-numList[k-1].Max > 3 { //如果是选择: 1-5 、 10次以上
			notRangeMin = numList[k-1].Max
			notRangeMax = numList[k].Min
		}

	}
	return rangeMin, rangeMax, notRangeMin, notRangeMax
}

// 获取合作公司列表
func (s *contactService) getCooperationName(ctx context.Context, developerName string, cooperationParam *opensearch_remote2.GetCooperationListRequest, req *pb.ContactListRequest) []*bigdata_remote.GetCooperationCompanyItem {
	if developerName == "" || cooperationParam == nil {
		return nil
	}
	request := &bigdata_remote.GetCooperationCompanyRequest{
		DeveloperName:        developerName,
		CooperationTimeStart: req.CooperationTimeStart,
		CooperationTimeEnd:   req.CooperationTimeEnd,
		PageNum:              1,
		PageSize:             10000, //暂设置10000，如果数据量不够，再调整
	}
	if cooperationParam.SearchKeyword != "" {
		request.SearchContent = "%" + cooperationParam.SearchKeyword + "%"
	}
	//处理合作数量where条件
	rangeMin, rangeMax, notRangeMin, notRangeMax := s.getNumCondition(req.CooperationCount)
	if notRangeMin != 0 {
		request.NotRangeMin = strconv.Itoa(int(notRangeMin))
		request.NotRangeMax = strconv.Itoa(int(notRangeMax))
	}
	if rangeMin != 0 {
		request.RangeMin = strconv.Itoa(int(rangeMin))
		request.RangeMax = strconv.Itoa(int(rangeMax))
	}
	//获取合作单位
	bigDataCooperationCompanyResponse, err := s.bigDataServiceRepo.GetCooperationCompany(ctx, request)
	if err != nil {
		stark.Logger.Error(ctx, "bigdata GetCooperationCompany,err:%s", err.Error())
	}

	if bigDataCooperationCompanyResponse != nil && bigDataCooperationCompanyResponse.Total > 0 {
		item := opensearch_remote2.CooperationListCompany{}
		for _, value := range bigDataCooperationCompanyResponse.List {
			item.CompanyName = value.SupplierName
			item.OrganizingCode = value.SupplierOrganizingCode
			cooperationParam.CompanyList = append(cooperationParam.CompanyList, item)
		}
		return bigDataCooperationCompanyResponse.List
	}

	return make([]*bigdata_remote.GetCooperationCompanyItem, 0)
}

// 获取合作公司列表
func (s *contactService) getCooperationNameOld(ctx context.Context, developerName string, cooperationParam *opensearch_remote2.GetCooperationListRequest, req *pb.ContactListRequest) []*dto.CooperationCompanyData {
	request := dto.BigDataCooperationCompanyRequest{
		DeveloperName:        developerName,
		CooperationTimeStart: req.CooperationTimeStart,
		CooperationTimeEnd:   req.CooperationTimeEnd,
	}
	if cooperationParam.SearchKeyword != "" {
		request.SearchContent = "%" + cooperationParam.SearchKeyword + "%"
	}
	//处理合作数量where条件
	rangeMin, rangeMax, notRangeMin, notRangeMax := s.getNumCondition(req.CooperationCount)
	if notRangeMin != 0 {
		request.NotRangeMin = strconv.Itoa(int(notRangeMin))
		request.NotRangeMax = strconv.Itoa(int(notRangeMax))
	}
	if rangeMin != 0 {
		request.RangeMin = strconv.Itoa(int(rangeMin))
		request.RangeMax = strconv.Itoa(int(rangeMax))
	}
	//获取合作单位
	requestMap, _ := simplecopier.StructToMapByJsonTag(request)
	cooperationCompanyResult := &dto.BigDataCooperationCompanyResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathDeveloperCooperationCompany, requestMap, map[string]string{}).EndStruct(&cooperationCompanyResult)
	if len(errs) > 0 {
		stark.Logger.Error(ctx, "获取数芯接口", constants.BigDataPathCompanyContactCnt, "异常,err:", errs[0])
	}
	if cooperationCompanyResult.ErrCode == 0 && len(cooperationCompanyResult.Data) > 0 {
		item := opensearch_remote2.CooperationListCompany{}
		for _, value := range cooperationCompanyResult.Data {
			item.CompanyName = value.SupplierName
			item.OrganizingCode = value.OrganizingCode
			cooperationParam.CompanyList = append(cooperationParam.CompanyList, item)
		}
	}

	return cooperationCompanyResult.Data
}

// GetExportCooperationTotal 客户详情-合作供方，获取总数
func (s *contactService) GetExportCooperationTotal(ctx context.Context, condition interface{}) (total int64, err error) {
	var request *pb.ContactListRequest
	switch condition.(type) {
	case *pb.ContactListRequest:
		request = condition.(*pb.ContactListRequest)
	case string:
		request = &pb.ContactListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "客户详情合作供方获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}

	request.Page = 1
	request.PageSize = 1

	resp, err := s.ContactList(ctx, request)
	if err != nil {
		return 0, err
	}
	if resp == nil {
		return 0, nil
	}
	total = int64(resp.CooperationCompanyTotal)
	return
}

// QueryExportCooperationBatchData 客户详情-合作供方分批获取数据
func (s *contactService) QueryExportCooperationBatchData(ctx context.Context, condition interface{}, batchNum, batchSize int32) (rowTitle []string, rowData [][]string, err error) {
	rowTitle = strings.Split(constants.OrderTypeCustomerDetailCooperationExportFields, "，")
	var request *pb.ContactListRequest
	switch condition.(type) {
	case *pb.ContactListRequest:
		request = condition.(*pb.ContactListRequest)
	case string:
		request = &pb.ContactListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "客户详情合作供方获取数据错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}

	request.Page = batchNum
	request.PageSize = batchSize

	resp, err := s.ContactList(ctx, request)
	if err != nil {
		return
	}
	if resp == nil {
		return
	}

	for _, item := range resp.CooperationCompany {
		rowData = append(rowData, []string{
			item.CooperationCompanyName,                     //供方名称，
			strings.Split(item.LastCooperationTime, " ")[0], //最新合作时间，
			fmt.Sprintf("%d", item.CooperationCnt),          //合作数量
		})
	}

	return
}
